//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using Eas.WebCrawler.Interfaces;

namespace Eas.WebCrawler.PlugIns.Selectors {
    /// <summary>Determines wehether or not to follow links based on whether or not the Request uris contain any of a set of strings inside themselves.</summary>
    public class NameSelector : ConditionalSelector {
        private string[] _Names;

        /// <summary>Constructs a <see cref="NameSelector"/> from two selectors and a list of substrings (names).</summary>
        /// <param name="trueSelector">The selector to call if any of the names are found in the request's Uri.</param>
        /// <param name="falseSelector">The selector to call if none of the names are found in the request's Uri.</param>
        /// <param name="names">The substrings to look for.</param>
        public NameSelector(Eas.WebCrawler.Interfaces.LinkSelector trueSelector, Eas.WebCrawler.Interfaces.LinkSelector falseSelector, params string[] names)
            : base(trueSelector, falseSelector, null) {
            
            _Names = new string[names.Length];
            for (int i = 0; i < names.Length; i++) {
                _Names[i] = names[i].ToUpperInvariant();
            }
            Array.Sort<string>(_Names);

            this.ConditionalDelegate = new RequestFilterDelegate(NamesFound);
        }

        /// <summary>The substrings to look for in the request's Uri.</summary>
        public IEnumerable<string> Names {
            get { return _Names; }
        }

        private bool NamesFound(Request request) {

            string uri = request.Uri.ToString().ToUpperInvariant();

            for (int i = 0; i < _Names.Length; ++i) {
                if (uri.IndexOf(_Names[i], StringComparison.Ordinal) > -1)
                    return true;
            }
            return false;
        }
    }
}
